import React, { useState, useRef } from 'react';
import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { t } from '@lingui/macro';
import { Button, Dialog, Drawer, Message } from '@alifd/next';
import { useStore } from '@/hooks';
import { uniqueId } from 'lodash';
import { column, toSelectDataSource, ENUMS } from './stores/definitions';
import { observer } from 'mobx-react-lite';
import { toJS } from 'mobx';
import DataForm from './components/DataForm';
import MoreFuncDropDown from '@/components/MoreFuncDropDown';
import CloneRuleModal from './components/CloneRuleModal';

const tableId = uniqueId('tauTable-');

const TITLE_TEXT = {
  view: t`查看管理群`,
  edit: t`编辑管理群`,
  add: t`添加管理群`,
};

const DriverGroup = () => {
  const { driverGroupStore: store, loginStore } = useStore();
  const [modal, setModal] = useState({
    show: null,
    record: null,
  });

  console.log(toJS(store.refund));

  /**
   * @description 处理搜索条件
   * @param {*} params
   */
  const handleOnSearch = (params) => {
    const { onData, enable, ...searchArgs } = params.values;
    const [from, to] = onData || [];
    store.search = {
      from,
      to,
      ...(enable ? { enable: JSON.parse(enable) } : null),
      ...searchArgs,
    };
  };

  /**
   * 关闭侧边卡片
   */
  const handleCancel = () => {
    setModal({ show: null });
  };

  const handleEdit = (r) => {
    console.log(r);
    setModal({ show: 'edit', record: r });
  };

  const handleAddManage = () => {
    setModal({ show: 'add', record: null });
  };

  const handleView = (r) => {
    setModal({ show: 'view', record: r });
  };

  const handleCloneRule = (r) => {
    setModal({ show: 'clone', record: r });
  };

  // 点击跳转到详情
  const handleToBob = async (record) => {
    const code = await loginStore.getCode();
    global.Cookie.set('code', code, { path: '/', maxAge: 60 }); // 有效期1分钟
    window.open(`${global.getEnvCfg().bobUrl}/?id=${record.id}`, 'bob');
  };

  const handleDelete = (r) => {
    const { id } = r;
    Dialog.confirm({
      title: t`确定删除吗?`,
      onOk: async () => {
        try {
          store.remove(id);
          Message.success({ content: t`删除成功` });
        } catch (error) {
          Message.error({ content: t`删除失败`, duration: 7000 });
          throw error;
        }
      },
    });
  };

  const handleOnSubmit = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.create(toJS(result));
        Message.success({ content: t`添加成功` });
      } catch (e) {
        Message.error({ content: t`添加失败`, duration: 7000 });
        throw e;
      }
    }
    handleCancel();
  };

  const handleOnUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.update(toJS(result));
        Message.success({ content: t`更新成功` });
      } catch (e) {
        Message.error({ content: t`更新失败`, duration: 7000 });
        throw e;
      }
    }
    handleCancel();
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        actions={[
          {
            name: 'btn-placeActivity',
            title: t`添加群管理`,
            type: 'primary',
            onClick: handleAddManage,
          },
        ]}
        searchItems={[
          {
            name: 'onData',
            type: 'date-range',
            props: {
              placeholder: [t`开始时间`, t`结束时间`],
            },
          },
          {
            name: 'enable',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.enable),
              placeholder: t`状态`,
            },
          },
        ]}
        keywordSearch={{
          // enabled: false,
          placeholder: t`请输入关键字搜索`,
        }}
        className="action-panel"
      />
      <div className="content">
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          onFetch={(pg) => {
            store.pg = pg;
          }}
          loading={store.loading}
          dataSource={toJS(store.refund)}
          columns={[
            { title: t`编号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('groupName', {
              cell: (v, __, r) => (
                <Button text type="primary" onClick={() => handleView(r)}>
                  {v}
                </Button>
              ),
            }),
            column('managerGroup', {}),
            column('accountingGroup', {}),
            column('enable', {}),
            column('crDate', {}),
            {
              title: t`操作`,
              dataIndex: 'refundNumber',
              width: 180,
              cell: (_, __, r) => {
                const menu = [
                  {
                    title: t`编辑`,
                    onClick: () => handleEdit(r),
                  },
                  {
                    title: t`删除`,
                    onClick: () => handleDelete(r),
                    color: 'red',
                  },
                  {
                    title: t`详情`,
                    onClick: () => handleToBob(r),
                  },
                  {
                    title: t`克隆规则`,
                    onClick: () => handleCloneRule(r),
                  },
                ];
                return <MoreFuncDropDown dropdownItems={menu} />;
              },
            },
          ]}
        />
      </div>
      <Drawer
        visible={modal.show === 'add' || modal.show === 'edit' || modal.show === 'view'}
        title={TITLE_TEXT[modal.show]}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal({ ...modal, toClose: `toClose$${Date.now()}` })}
        width={'100%'}
      >
        <DataForm
          modal={modal}
          id={modal.record?.id}
          onSubmit={modal.show === 'add' ? handleOnSubmit : handleOnUpdate}
          onCancel={handleCancel}
        />
      </Drawer>
      <CloneRuleModal modal={modal} onSubmit={handleOnUpdate} onCancel={handleCancel} />
    </TauPage>
  );
};

export default observer(DriverGroup);
